<template>
  <el-upload
    class="upload-demo"
    action=""
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :http-request="uploadImg"
    :file-list="fileList"
    list-type="picture"
    :before-upload="beforeAvatarUpload"
  >
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5Mb</div>
  </el-upload>

</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  data() {
    return {
    }
  },
  methods: {
    uploadImg(params) {
      console.log('上传图片', params)
      const cos = new COS({
        SecreyId: 'AKIDb4OVQ8dx63oS0NYZQ8iLwOev42mJemkX',
        SecreyKey: 'e52pRqRrpdIrFTit8A6sRn7HGwZ7f8d1'
      })
      cos.putObject({
        Bucket: 'hr-management-1312375448', // 存储桶的名称
        Region: 'ap-nanjing', // 存储桶所在地域
        Key: params.file.name, // 文件名称
        StorageClass: 'STANDARD', // 存储类型 -模式（标准模式）
        Body: params.file// 文件对象
      }, (err, data) => {
        // err 错误信息
        console.log('上传图片错误', err)
        // data 上传成功之后的数据
        console.log('上传图片成功', data)
      }

      )
    },

    beforeAvatarUpload(file) {
      const isImage = file.type === ['image/jpeg', 'image/png', 'image/jpg', 'image/gif', 'image/webp'].includes(file.type)
      console.log(isImage)
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG、PNG、GIF、WEBP 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isImage && isLt5M
    }
  }
}
</script>
